import { View } from "@tarojs/components";
import { AtActionSheet, AtButton, AtList, AtListItem } from "taro-ui"
import cardImg from '@/assets/image/card-img.png'
import { useEffect, useRef, useState } from 'react'
import Category from "./components/category";
import TagsPanel from "./components/tags-panel";
import './index.less'
import MyImage from "../my-image";
import { dataType } from '../../types/edit-clothes'

const listData = [
    {
        text: '分类',
        val: 1
    },
    {
        text: '季节',
        val: 2
    },
]

type propsType = {
    data?: dataType
}

const defaultData = {
    name: '',
    img: [''],
    details: {
        category: { val: -1 },
        season: { val: -1 }
    }
}


export default function EditClothes(props: propsType) {
    const [isOpened, setIsOpened] = useState(false)
    const [curVal, setCurVal] = useState({ val: 0, key: 0 })
    const [listText, setListText] = useState<Array<string>>([])
    const [data] = useState(props?.data ?? defaultData)

    const categoryRef = useRef()
    const tagsPanelRef = useRef()
    const ref = useRef()

    useEffect(() => {
        listData.forEach(() => {
            listText.push('')
        })
    }, [ref])

    function handleClick(val: number, key: number) {
        setCurVal({ val, key })
        setIsOpened(!isOpened)
    }

    function handleSubmit() {
        let current: undefined | { curVal: { text: '' } }
        switch (curVal.key) {
            case 0:
                current = categoryRef.current
                break
            case 1:
                current = tagsPanelRef.current
                break
        }
        if (current) {
            listText[curVal.key] = current.curVal.text
            setListText(listText)
        }
        setIsOpened(false)
    }

    return (
        <View className='edit-clothes' ref={ref}>
            <View className='img-wrap'>
                <MyImage src={cardImg} className='img' mode='aspectFill' />
            </View>
            <AtList>
                {
                    listData.map(({ text, val }, k) => {
                        return <AtListItem title={text} onClick={() => handleClick(val, k)} arrow='right' key={k} extraText={listText[k]}></AtListItem>
                    })
                }
            </AtList>
            <AtActionSheet isOpened={isOpened} onClose={() => setIsOpened(!isOpened)}>
                <View className='at-row at-row__justify--center title'>
                    {listData[curVal.key].text}
                </View>
                {curVal.val == 1 && <Category ref={categoryRef} curVal={data.details.category} />}
                {curVal.val == 2 && <TagsPanel ref={tagsPanelRef} curVal={data.details.season} />}
                <View className='btn'><AtButton type='primary' onClick={() => handleSubmit()}>确定</AtButton></View>
            </AtActionSheet>
        </View >
    )
}